<template>
  <div>
    <el-card shadow="never" style="margin-top: 20px;">
          <!-- <el-row type="flex" justify="end" style="margin-bottom: 15px;">
            <el-button type="primary" size="mini" @click="SUPPLIER.fn.add()">新增</el-button>
            <el-button type="primary" size="mini" @click="SUPPLIER.fn.getInfo()">刷新列表</el-button>
          </el-row> -->
      <el-table border 
        :data="SUPPLIER.tableData" 
        highlight-current-row
        @current-change="SUPPLIER.fn.handleSelect"
        style="width: 100%">
        <el-table-column
          type="index"
          width="28">
        </el-table-column>
        <el-table-column prop="name" align="center" label="名称" width="100px" />
        <el-table-column prop="supplierName" align="center" label="俗名" width="100px" />
        <el-table-column prop="timeZone" align="center" label="时区" width="100px" />
        <el-table-column prop="ip" align="center" label="ip" width="120px" />
        <el-table-column prop="port1" align="center" label="port1" width="60px" />
        <el-table-column prop="port2" align="center" label="port2" width="60px" />
        <el-table-column prop="apikey" align="center" label="秘钥" width="200px" />
        <!-- <el-table-column prop="urlGupiao" align="center" label="url股票" width="100px" />
        <el-table-column prop="urlWaihui" align="center" label="url外汇" width="100px" />
        <el-table-column prop="urlShangpin" align="center" label="url商品" width="100px"  />
        <el-table-column prop="urlHuobi" align="center" label="url货币" width="100px" /> -->
        <el-table-column prop="" align="center" label="状态" width="80px">
          <template v-slot="{ row }">
            <span v-if = "row.isActive" style = "color:green">启用</span>
            <span v-if = "!row.isActive" style = "color:red">禁用</span>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="操作" width="160px">
          <template v-slot="{ row }">
            <!-- <el-button type="warning" size="mini" @click="SUPPLIER.fn.modify(row)">编辑</el-button> -->
            <el-button v-if = "!row.isActive" type="success" size="mini" @click="SUPPLIER.fn.active(row.id,1)">启用</el-button>
            <el-button v-if = "row.isActive"  type="danger" size="mini" @click="SUPPLIER.fn.active(row.id,0)">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-card>
      <el-card shadow="never" style="margin-top: 15px;">
            <el-form :inline="true">
                
                <el-form-item label="数据源:">
                  <div>
                    <el-checkbox-group v-model="TYPE.paramFrom.supplierIds" size="medium">
                      <el-checkbox-button 
                      v-for="item in SUPPLIER.tableData" 
                      :key="item.id"
                      :label="item.id" >{{item.name}}</el-checkbox-button>

                    </el-checkbox-group>
                  </div>
                </el-form-item>
                <br>
                <el-form-item label="一级菜单:" style="width: 300px;">
                    <el-input v-model="TYPE.paramFrom.type2" placeholder="请输入内容" size="mini" style="width: 80px;"></el-input>
                </el-form-item>
                <el-form-item label="二级菜单:" style="width: 300px;">
                    <el-input v-model="TYPE.paramFrom.type3" placeholder="请输入内容" size="mini" style="width: 80px;"></el-input>
                </el-form-item>
                <br>
                <el-form-item label="中文名称:" style="width: 300px;">
                    <el-input v-model="TYPE.paramFrom.cnName" placeholder="请输入内容" size="mini" style="width: 80px;"></el-input>
                </el-form-item>
                <el-form-item label="英文名称:" style="width: 300px;">
                    <el-input v-model="TYPE.paramFrom.enName" placeholder="请输入内容" size="mini" style="width: 80px;"></el-input>
                </el-form-item>
                
            </el-form>
        </el-card>

      <el-card shadow="never" style="margin-top: 5px;">
          <el-row type="flex" justify="end" style="margin-bottom: 15px;">
            <el-button type="primary" size="mini" @click="TYPE.fn.add()">新增</el-button>
            <el-button type="primary" size="mini" @click="TYPE.fn.activeSuppliersByIds()">批量切换已选择至{{ SUPPLIER.selectedRow.name }}</el-button>
            <el-button type="primary" size="mini" @click="TYPE.fn.activeSuppliersBySearch()">批量切换已查询至{{ SUPPLIER.selectedRow.name }}</el-button>

          </el-row>
      <el-table border :data="TYPE.tableData" style="width: 100%"
      @selection-change="TYPE.fn.handleSelect">
        <el-table-column
      type="selection"
      width="35">
    </el-table-column>
        <el-table-column prop="type2" align="center" label="一级菜单" width="100px" />
        <el-table-column prop="type3" align="center" label="二级菜单" width="100px" />
        <el-table-column prop="code" align="center" label="输入" width="100px" />
        <el-table-column prop="code2" align="center" label="输出" width="120px" />
        <el-table-column prop="enName" align="center" label="英文名" width="200px" />
        <el-table-column prop="cnName" align="center" label="中文名" width="200px" />
        <el-table-column prop="orderIndex" align="center" label="排序" width="80px" />
        <el-table-column prop="" align="center" label="图标" width="100px">
          <template v-slot="{ row }">
            <img v-if="row.img1" :src= "imgBaseUrl + row.img1" width="30px"/>
            <img v-if="row.img2" :src= "imgBaseUrl + row.img2" width="30px"/>
          </template>
        </el-table-column>
        
        
        <el-table-column prop="" align="center" label="数据源切换" width="180px">
          <template v-slot="{ row }">
            <div v-for="supplier in row.suppliers" :key="supplier.typeSupplierId">
              <el-button v-if="supplier.isActive && supplier.typeSupplierIsActive" size="mini" 
              @click="TYPE.fn.activeTypeSupplier(supplier.typeSupplierId,0)"
              type="success" style="margin: 3px;">{{supplier.name}}</el-button>

              <el-button v-if="supplier.isActive && !supplier.typeSupplierIsActive" size="mini" 
              @click="TYPE.fn.activeTypeSupplier(supplier.typeSupplierId,1)"
              type="danger" style="margin: 3px;">{{supplier.name}}</el-button>

              <el-button v-if="!supplier.isActive" size="mini" 
              
              type="info" style="margin: 3px;">{{supplier.name}}</el-button>

              <i class="el-icon-edit" style="margin-left: 10px;" @click="TYPE.fn.typeSupplierById(supplier.typeSupplierId)"></i>
              <i class="el-icon-delete" style="margin-left: 10px;" @click="TYPE.fn.delSupplierByTypeSupplierId(supplier.typeSupplierId)"></i>
            </div>
              

          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="状态" width="80px">
          <template v-slot="{ row }">
            <span v-if = "row.isActive" style = "color:green">启用</span>
            <span v-if = "!row.isActive" style = "color:red">禁用</span>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="操作" width="240px" >
        <template v-slot="{ row }">
            <el-button type="warning" size="mini" @click="TYPE.fn.modify(row)" style="margin: 3px;">编辑</el-button>
            <el-button type="danger" size="mini" @click="TYPE.fn.del(row.id)" style="margin: 3px;">删除</el-button>
            <el-button v-if = "!row.isActive" type="success" size="mini" @click="TYPE.fn.active(row.id,1)" style="margin: 3px;">启用</el-button>
            <el-button v-if = "row.isActive"  type="danger" size="mini" @click="TYPE.fn.active(row.id,0)" style="margin: 3px;">禁用</el-button>
            <el-button size="mini" type="info" @click="TYPE.fn.addSupplier(row)" style="margin: 3px;">添加数据源:{{ SUPPLIER.selectedRow.name }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <paging :page-size="TYPE.query.pageSize" 
        :total="TYPE.total" 
        :currentPage="TYPE.currentPage"
        @size-change="TYPE.fn.handleSizeChange"
        @current-change="TYPE.fn.handleCurrentChange" />
      <typeAdd ref="typeAdd" 
        :dialogTitle="TYPE.dialogTitle" 
        :dialog-visible.sync="TYPE.dialogVisible" 
        :form="TYPE.form" 
        :options="TYPE.options"
        :data="TYPE"
        @getStaffList="TYPE.fn.getInfo" />
        <typeSupplierAdd ref="typeSupplierAdd" 
        :dialogTitle="TYPE.typeSupplierDialogTitle" 
        :dialog-visible.sync="TYPE.typeSupplierDialogVisible" 
        :form="TYPE.typeSupplierForm" 
        :data="TYPE"
        @getStaffList="TYPE.fn.getInfo" />
    </el-card>


  </div>
</template>
<script>
import typeAdd from './type/typeAdd.vue'
import typeSupplierAdd from './typeSupplier/typeSupplierAdd.vue'
// import etfsAdd from './etfs/etfsAdd.vue'
import paging from '@/components/paging.vue'
import {  
  SUPPLIERApi,
  TYPEApi,
} from "./supplierAndDataIndex.js";
import baseData from '@/baseData'
import Cookies from 'js-cookie'
import { TOKEN_KEY } from "@/constants/KEY";
export default {
    name: 'SupplierAndData',
    components: {
      paging,
      typeAdd,
      typeSupplierAdd,
      // etfsAdd,
    },
    data() {
      return {
       imgBaseUrl:baseData.basePathUser+'/tbFile/fileById?id=',
       //imgSvgBaseUrl:baseData.basePathUser+'/tbFile/fileByIdSvg/',
       SUPPLIER:{
        dialogTitle:'新增1',
        dialogVisible: false,
        form:{},
        selectedRow:{},
        action:baseData.basePathAdmin+"/CriteriaAPIStructure/uploadPatternsCFTCExcel",
        paramFrom:{
          
        },
        tableData:[],
        options: [],
        query:{
          pageSize:10,
          page:1
        },
        currentPage:1,
        total:0,
        fn:{submit:{}},
      },
      TYPE:{
        dialogTitle:'新增',
        dialogVisible: false,
        form:{},
        typeSupplierDialogTitle:'编辑',
        typeSupplierDialogVisible: false,
        typeSupplierForm:{},
        selectedRows:[],
        action:baseData.basePathAdmin+"/CriteriaAPIStructure/uploadPatternsETFsExcel",
        paramFrom:{
          supplierIds:[],
          type2:'',
          type3:'',
          enName:'',
          cnName:'',
        },
        tableData:[],
        options: [],
        query:{
          pageSize:10,
          page:1
        },
        currentPage:1,
        total:0,
        fn:{}, 
       },
  
       header: {
        Authentication: Cookies.get(TOKEN_KEY)
      },
      }
    },
  
    mounted() {
      Array.prototype.contain = function(val)
    {
        for (var i = 0; i < this.length; i++)
        {
          if (this[i] == val)
          {
          return true;
          }
        }
        return false;
    }
      window.common = this
      this.SUPPLIER.fn = this.SUPPLIERfn()
      this.TYPE.fn =this.TYPEfn()
      this.SUPPLIER.fn.init()
      this.TYPE.fn.init()
      this.SUPPLIER.fn.getInfo()
      this.TYPE.fn.getInfo()
    },
    watch:{


      'TYPE.paramFrom': {
        handler(newValue, oldValue) {
          this.TYPE.fn.query()
          //console.log('User changed:', newValue);
        },
        // 是否在选项声明时立即触发
        immediate: false,
        // 是否深度监听
        deep: true
      },
      
    },
    methods: {
      handleClick(tab, event) {
        //console.log(tab, event);
      },
      SUPPLIERfn(){
        const that = this;
        let that_data = that.SUPPLIER
        const that_api = SUPPLIERApi()
        
        const fn = {
          async active(id,isActive){
            const data = await that_api.active({id,isActive})
            that_data.fn.getInfo()
            that.TYPE.fn.getInfo()
          },
          init(){
            that_data = that.SUPPLIER
          },
          handleSelect(row){
            if(!row){
              row = {}
            }
            that_data.selectedRow = row;
          },
          handleSuccess(res){
            that.$message({
                type: 'success',
                message: res.msg
              })
            that_data.fn.query()
          },
          add(){
            that_data.dialogTitle = '新增'
            that_data.form = {
              positionType:'商业持仓',
              variety:'黄金',
            }
            that_data.dialogVisible = true
          },
          modify(row){
            that_data.dialogTitle = '编辑'
            that_data.form = row
            that_data.dialogVisible = true
          },
          async submit(){

            if(that_data.form.id){
              const res = await that_api.edit(that_data.form);
              that_data.dialogVisible = false
              that_data.fn.getInfo();
            }else{
              const res = await that_api.add(that_data.form);
              that_data.dialogVisible = false
              that_data.fn.getInfo();
            }
            
          },
          async selectAllVariety(){
            const data = await that_api.selectAllVariety()
            const options = []
            data.forEach(element => {
              options.push({
                value: element,
                label: element
              })
            });
            that_data.options = options
          },
          query(){
            that_data.query.page = 1
            that_data.currentPage = 1
            that_data.fn.getInfo();
          },
          async getInfo(){
            const data = await that_api.getPage()
            that_data.tableData = data
          },
          handleSizeChange(){
            
          },
          handleCurrentChange(val){
            that_data.currentPage = val
            that_data.query.page = val
            that_data.fn.getInfo()
          },
          del(id){
            that.$confirm('你确定要删除吗?', '删除', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              const res = await that_api.del({id})
              that_data.fn.getInfo()
              
            }).catch(() => {
              that.$message({
                type: 'success',
                message: '已取消删除'
              })
            })
          }
        }
        return fn
      },
      TYPEfn(){
        const that = this;
        let that_data = that.TYPE
        const that_api = TYPEApi()
        const fn = {
          init(){
            that_data = that.TYPE
          },
          
          async active(id,isActive){
            const res = await that_api.active({id,isActive})
            that.$message({
                    type: 'info',
                    message: res
                  })
            that_data.fn.getInfo();
          },
          async activeTypeSupplier(typeSupplierId,isActive){

            let info ;
            if(isActive){
              info = {
                msg:'启用时，会将此品种的其他数据源禁用，确定吗？',
                title:'启用',
              }
              
            }else{
              info = {
                msg:'禁用后，门户将无法看到此品种，确定吗？',
                title:'禁用',
              }
            }
            that.$confirm(info.msg, info.title, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              const res = await that_api.activeTypeSupplier({typeSupplierId,isActive})
              that.$message({
                      type: 'info',
                      message: res
                    })
              that_data.fn.getInfo();
              
            }).catch(() => {
              that.$message({
                type: 'success',
                message: '已取消'+msg.title
              })
            })

            
          },
          handleSelect(rows){
            if(!rows){
              rows = []
            }
            that_data.selectedRows = rows;
            console.log("rows",rows)
          },
          async activeSuppliersByIds(){
            if(!that.SUPPLIER.selectedRow.id){
              that.$message({
                type: 'error',
                message: "请选中上方一个要添加的数据源"
              })
              return
            }
            if(!that.SUPPLIER.selectedRow.isActive){
              that.$message({
                type: 'error',
                message: "选中的数据源未启用"
              })
              return
            }
            const supplierId = that.SUPPLIER.selectedRow.id
            if(!that_data.paramFrom.supplierIds.contain(supplierId)){
              that.$message({
                type: 'error',
                message: "选择条件中必须选中"+that.SUPPLIER.selectedRow.name
              })
              return
            }
            if(that_data.selectedRows.length==0){
              that.$message({
                type: 'error',
                message: "请选中至少一条需要改变品种"
              })
              return
            }
            
            that.$confirm('你确定要将已选择品种切换至'+that.SUPPLIER.selectedRow.name+'吗?', '切换数据源', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              let typeSupplierIds = ''
              for(const row of that_data.selectedRows){
                for(const sup of row.suppliers){
                  if(sup.id == supplierId){
                    typeSupplierIds += ','+sup.typeSupplierId
                    break
                  }
                }
              }
              that_data.selectedRows
              const res = await that_api.activeSuppliersByTypeSupplierIds({typeSupplierIds})
              that_data.fn.getInfo()
              
            }).catch(() => {
              that.$message({
                type: 'success',
                message: '已取消删除'
              })
            })
          },
          async activeSuppliersBySearch(){
            if(!that.SUPPLIER.selectedRow.id){
              that.$message({
                type: 'error',
                message: "请选中上方一个要添加的数据源"
              })
              return
            }
            if(!that.SUPPLIER.selectedRow.isActive){
              that.$message({
                type: 'error',
                message: "选中的数据源未启用"
              })
              return
            }
            const supplierId = that.SUPPLIER.selectedRow.id
            if(!that_data.paramFrom.supplierIds.contain(supplierId)){
              that.$message({
                type: 'error',
                message: "选择条件中必须选中"+that.SUPPLIER.selectedRow.name
              })
              return
            }
            that.$confirm('你确定要将已查询品种切换至'+that.SUPPLIER.selectedRow.name+'吗?', '切换数据源', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              let typeSupplierIds = ''
              for(const row of that_data.selectedRows){
                for(const sup of row.suppliers){
                  if(sup.id == supplierId){
                    typeSupplierIds += ','+sup.typeSupplierId
                    break
                  }
                }
              }
              that_data.selectedRows
              const res = await that_api.activeSuppliersBySearch({
              ...that_data.query,
              supplierId,
              tbType:that_data.paramFrom})
              that_data.fn.getInfo()
              
            }).catch(() => {
              that.$message({
                type: 'success',
                message: '已取消删除'
              })
            })
          },
          addSupplier(row){
            if(!that.SUPPLIER.selectedRow.id){
              that.$message({
                type: 'error',
                message: "请选中上方一个要添加的数据源"
              })
              return
            }
            const suppliers = row.suppliers
            if(suppliers != null){
              for(let i=0;i<suppliers.length;i++){
                const supplier = suppliers[i]
                if(supplier.id === that.SUPPLIER.selectedRow.id){
                  that.$message({
                    type: 'error',
                    message: "不能重复添加数据源"
                  })
                  return
                }
              }
            }
            that_data.fn.addSupplierByTypeId(row.id,that.SUPPLIER.selectedRow.id);
          },
          async addSupplierByTypeId(typeId,supplierId){
            const res = await that_api.addSupplierByTypeId({typeId,supplierId})
              that.$message({
                    type: 'info',
                    message: res
                  })
            that_data.fn.getInfo();
          },
          async delSupplierByTypeSupplierId(typeSupplierId){
            const res = await that_api.delSupplierByTypeSupplierId({typeSupplierId})
              that.$message({
                    type: 'info',
                    message: res
                  })
            that_data.fn.getInfo();
          },
          async typeSupplierById(typeSupplierId){
            const res = await that_api.TypeSupplierById({id:typeSupplierId})
            if(res.id){
              that_data.typeSupplierForm = res
              that_data.typeSupplierDialogVisible = true
            }
          },
          handleSuccess(res){
            that.$message({
                type: 'success',
                message: res.msg
              })
            that_data.fn.query()
          },
          add(){
            that_data.dialogTitle = '新增'
            that_data.form = {
              
              gold:'黄金',
            }
            that_data.dialogVisible = true
          },
          modify(row){
            that_data.dialogTitle = '编辑'
            that_data.form = row
            that_data.dialogVisible = true
          },
          async submit(){

            if(that_data.form.id){
              const res = await that_api.edit(that_data.form)
              that_data.dialogVisible = false
              that_data.fn.getInfo();
            }else{
              const res = await that_api.add(that_data.form)
              that_data.dialogVisible = false
              that_data.fn.getInfo();
            }
            
          },
          async submitTypeSupplier(){

            if(that_data.typeSupplierForm.id){
              const res = await that_api.typeSupplierEdit(that_data.typeSupplierForm)
              that_data.typeSupplierDialogVisible = false
              that_data.fn.getInfo();
            }else{
              
            }

          },
          async selectAllVariety(){
            const data = await that_api.selectAllVariety()
            const options = []
            data.forEach(element => {
              options.push({
                value: element,
                label: element
              })
            });
            that_data.options = options
          },
          query(){
            that_data.query.page = 1
            that_data.currentPage = 1
            that_data.fn.getInfo();
          },
          async getInfo(){
            const data = await that_api.getPage({
              ...that_data.query,
              tbType:that_data.paramFrom})
            that_data.tableData = data.records
            that_data.total = data.total
          },
          handleSizeChange(){
            
          },
          handleCurrentChange(val){
            that_data.currentPage = val
            that_data.query.page = val
            that_data.fn.getInfo()
          },
          del(id){
            that.$confirm('你确定要删除吗?', '删除', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              const res = await that_api.del({id})
              that_data.fn.getInfo()
              
            }).catch(() => {
              that.$message({
                type: 'success',
                message: '已取消删除'
              })
            })
          }
        }
        return fn
      },
      
    }
    
  }
  </script>
<style>
.el-table .el-table__body tr.current-row>td {
  background-color: #98e863; /* 绿色背景 */
}
</style>